﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DevExpress.Xpo;
using LprMiddleWare.Model;

namespace LprMiddleWare.DAL
{
    public class Repository
    {
        private ConcurrentDictionary<string, Lane> _lanes = new ConcurrentDictionary<string, Lane>();
        private List<TOG_DEVICE> _togCameras;
        private XPCollection<Department> _departments;
        private XPCollection<TogTollgate> _tollgates;
        private XPCollection<AORG> _organizations;
        private static Repository _instance;
        private XPCollection<LprType> _lprTypes;
        private static NLog.Logger _logger = NLog.LogManager.GetCurrentClassLogger();

        public IList<TOG_DEVICE> GetTogCameras(Session session)
        {
            if (_togCameras == null)
            {
                _togCameras = new XPCollection<TOG_DEVICE>(session).Where(t => t.SBLX == "1" || t.SBLX == "2").OrderBy(t => int.Parse(t.SBBH)).ToList();
            }

            return _togCameras;
        }

        public Lane GetLane(Session session, string kakouNo, string dirNo, string laneNo)
        {
            var key = kakouNo + "-" + dirNo + "-" + laneNo;
            if (_lanes.ContainsKey(key))
            {
                return _lanes[key];
            }

            var query = string.Format(
                "select a.kkbh, a.kkmc, a.kkdm, a.dwbh, o.orgname, b.kkbh fxbh, b.kkmc fxmc, c.kkbh cdbh, c.kkmc cdmc, c.xdsd,a.dlbh, a.dlmc, a.lkdm, a.lkmc,a.dwbh, a.xzqh, a.kkwz, c.sxjbh from tog_tollgate a, tog_tollgate b, tog_tollgate c,aorg o where a.kkbh=b.kkfbh and b.kkbh=c.kkfbh and a.kkbh<>'moniroot' and a.dwbh=o.orgid and c.kkbh = '{0}'", kakouNo + dirNo + laneNo);
            var res = session.ExecuteQuery(query);
            if (res.ResultSet.Length > 0 && res.ResultSet[0].Rows.Length > 0)
            {
                if (res.ResultSet[0].Rows[0].Values.Length >= 9)
                {
                    var msg = new StringBuilder();
                    var hasError = false;
                    var row = res.ResultSet[0].Rows[0];
                    if (row.Values[0] == null)
                    {
                        hasError = true;
                        msg.Append("卡口编号(tog_tollgate.kkbh) ");
                    }
                    if (row.Values[1] == null)
                    {
                        hasError = true;
                        msg.Append("卡口名称(tog_tollgate.kkmc) ");
                    }
                    if (row.Values[2] == null)
                    {
                        hasError = true;
                        msg.Append("卡口代码(tog_tollgate.kkdm) ");
                    }
                    if (row.Values[3] == null)
                    {
                        hasError = true;
                        msg.Append("单位代码(tog_tollgate.dwbh) ");
                    }
                    if (row.Values[4] == null)
                    {
                        hasError = true;
                        msg.Append("单位名称(aorg.orgname) ");
                    }
                    if (row.Values[5] == null)
                    {
                        hasError = true;
                        msg.Append("方向代码(tog_tollgate.kkbh) ");
                    }
                    if (row.Values[6] == null)
                    {
                        hasError = true;
                        msg.Append("方向名称(tog_tollgate.kkmc) ");
                    }
                    if (row.Values[7] == null)
                    {
                        hasError = true;
                        msg.Append("车道编号(tog_tollgate.kkbh) ");
                    }
                    if (row.Values[8] == null)
                    {
                        hasError = true;
                        msg.Append("车道名称(tog_tollgate.kkmc) ");
                    }

                    if (hasError)
                    {
                        var msgError = "车道 " + key + " 配置有错误, " + msg + "为空";
                        _logger.Error(msgError);
                    }
                    else
                    {
                        var c = new Lane();
                        c.No = laneNo;
                        c.KaKouNo = res.ResultSet[0].Rows[0].Values[0].ToString();
                        c.KakouName = res.ResultSet[0].Rows[0].Values[1].ToString();
                        c.KKMCDM = res.ResultSet[0].Rows[0].Values[2].ToString();
                        c.SSDWDM = res.ResultSet[0].Rows[0].Values[3].ToString();
                        c.SSDWMC = res.ResultSet[0].Rows[0].Values[4].ToString();
                        c.DirectionNo = res.ResultSet[0].Rows[0].Values[5].ToString();
                        c.DirectionName = res.ResultSet[0].Rows[0].Values[6].ToString();
                        c.LaneNo = res.ResultSet[0].Rows[0].Values[7].ToString();
                        c.LaneName = res.ResultSet[0].Rows[0].Values[8].ToString();
                        
                        _lanes.GetOrAdd(key, c);
                        return c;
                    }

                }
                else
                {
                    var msg = string.Format("车道 {0} 数据库配置有错误，车道字段不足9个", key);
                    _logger.Error(msg);
                }

            }
            else
            {
                var msg = string.Format("无法查询到车道 {0} 信息", key);
                _logger.Error(msg);
            }

            return null;
        }

        public LprType GetLprType(Session session, string lprTypeId)
        {
            if (_lprTypes == null)
            {
                _lprTypes = new XPCollection<LprType>(session);
            }

            return _lprTypes.FirstOrDefault(lpr => int.Parse(lpr.HPZLDM) == int.Parse(lprTypeId));
        }

        public Department GetDepartment(Session session, string departmentId)
        {
            if (_departments == null)
            {
                _departments = new XPCollection<Department>(session);
            }

            return _departments.FirstOrDefault(d => d.XZQHDM == departmentId);
        }

        public TogTollgate GetTollGate(Session session, string tollgateId)
        {
            if (_tollgates == null)
            {
                _tollgates = new XPCollection<TogTollgate>(session);
            }

            return _tollgates.FirstOrDefault(t => t.KKBH == tollgateId);
        }

        public AORG GetOrganization(Session session, string organizationId)
        {
            if (_organizations == null)
            {
                _organizations = new XPCollection<AORG>(session);
            }

            return _organizations.FirstOrDefault(o => o.ORGID == organizationId);
        }

        public static Repository Instance
        {
            get { return _instance ?? (_instance = new Repository()); }
        }
    }
}
